import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../models/character.dart';
import '../models/chat_message.dart';
import '../providers/user_provider.dart';
import '../providers/message_favorite_provider.dart';
import '../services/chat_service.dart';
import '../widgets/gradient_app_bar.dart';

class ChatPage extends StatefulWidget {
  final Character character;
  
  const ChatPage({
    Key? key,
    required this.character,
  }) : super(key: key);

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  final TextEditingController _messageController = TextEditingController();
  final List<ChatMessage> _messages = [];
  late Character _selectedCharacter;
  bool _isLoading = false;
  late ChatService _chatService;
  late UserProvider _userProvider;

  @override
  void initState() {
    super.initState();
    _selectedCharacter = widget.character;
    _initializeServices();
  }

  Future<void> _initializeServices() async {
    final prefs = await SharedPreferences.getInstance();
    _chatService = ChatService(prefs);
    _userProvider = Provider.of<UserProvider>(context, listen: false);
    await _loadChatHistory();
  }

  Future<void> _loadChatHistory() async {
    final history = await _chatService.getChatHistory(_selectedCharacter.id);
    if (history.isEmpty) {
      setState(() {
      });
    } else {
      setState(() {
        _messages.addAll(history);
      });
    }
    _scrollToBottom();
  }

  @override
  void dispose() {
    _messageController.dispose();
    super.dispose();
  }

  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_messages.isNotEmpty) {
        final scrollController = PrimaryScrollController.of(context);
        if (scrollController != null) {
          scrollController.animateTo(
            scrollController.position.maxScrollExtent,
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeOut,
          );
        }
      }
    });
  }

  Future<void> _sendMessage() async {
    if (_messageController.text.trim().isEmpty) return;
    if (_isLoading) return;
    
    // Check if user has enough coins
    if (_userProvider.coins < 10) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: const Text('Insufficient coins. Each message costs 10 coins. Visit the shop to get more coins.'),
          backgroundColor: Colors.orange,
          duration: const Duration(seconds: 3),
          behavior: SnackBarBehavior.floating,
          margin: const EdgeInsets.all(8),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
        ),
      );
      return;
    }
    
    final userMessage = _messageController.text;
    _messageController.clear();
    
    setState(() {
      _messages.add(
        ChatMessage(
          text: userMessage,
          isUser: true,
          timestamp: DateTime.now(),
          characterName: _selectedCharacter.name,
          characterDescription: _selectedCharacter.description,
          characterImageUrl: _selectedCharacter.imageUrl,
        ),
      );
      _isLoading = true;
    });
    
    _scrollToBottom();
    
    try {
      // Send message and get response
      final response = await _chatService.sendMessage(
        _selectedCharacter.id, 
        userMessage,
        characterName: _selectedCharacter.name,
        characterDescription: _selectedCharacter.description,
        characterPersonality: _selectedCharacter.personality,
      );
      
      // Deduct coins after successful response
      await _userProvider.deductCoins(10);
      
      // 更新角色的聊天次数
      final updatedCharacter = Character(
        id: _selectedCharacter.id,
        name: _selectedCharacter.name,
        description: _selectedCharacter.description,
        imageUrl: _selectedCharacter.imageUrl,
        isUnlocked: _selectedCharacter.isUnlocked,
        requiredCoins: _selectedCharacter.requiredCoins,
        type: _selectedCharacter.type,
        personality: _selectedCharacter.personality,
        topics: _selectedCharacter.topics,
        chatCount: _selectedCharacter.chatCount + 1,
      );
      
      setState(() {
        _selectedCharacter = updatedCharacter;
        _messages.add(
          ChatMessage(
            text: response,
            isUser: false,
            timestamp: DateTime.now(),
            characterName: _selectedCharacter.name,
            characterDescription: _selectedCharacter.description,
            characterImageUrl: _selectedCharacter.imageUrl,
          ),
        );
        _isLoading = false;
      });
      
      // Save chat history
      await _chatService.saveChatHistory(_selectedCharacter.id, _messages);
      _scrollToBottom();
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      
      String errorMessage = 'Failed to send message';
      if (e.toString().contains('Failed to send message')) {
        errorMessage = 'Network connection failed. Please check your connection and try again.';
      } else if (e.toString().contains('Invalid response format')) {
        errorMessage = 'Server response format error. Please try again later.';
      }
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(errorMessage),
          backgroundColor: Colors.red,
          duration: const Duration(seconds: 3),
          behavior: SnackBarBehavior.floating,
          margin: const EdgeInsets.all(8),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final bool hasEnoughCoins = _userProvider.coins >= 10;
    
    return Scaffold(
      appBar: GradientAppBar(
        title: _selectedCharacter.name,
        automaticallyImplyLeading: true,
        actions: [
          Center(
            child: Padding(
              padding: const EdgeInsets.only(right: 16.0),
              child: Row(
                children: [
                  const Icon(Icons.monetization_on, color: Colors.amber),
                  const SizedBox(width: 4),
                  Text(
                    '${_userProvider.coins}',
                    style: const TextStyle(
                      fontSize: 16,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.all(16),
              itemCount: _messages.length,
              itemBuilder: (context, index) {
                final message = _messages[index];
                return MessageBubble(message: message);
              },
            ),
          ),
          if (_isLoading)
            const Padding(
              padding: EdgeInsets.all(8.0),
              child: CircularProgressIndicator(),
            ),
          SafeArea(
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: BoxDecoration(
                color: Theme.of(context).cardColor,
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.1),
                    blurRadius: 4,
                    offset: const Offset(0, -2),
                  ),
                ],
              ),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: _messageController,
                      enabled: !_isLoading && hasEnoughCoins,
                      decoration: InputDecoration(
                        hintText: _isLoading 
                            ? 'Waiting for response...' 
                            : !hasEnoughCoins 
                                ? 'Insufficient coins (10 coins per message)'
                                : 'Type a message...',
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(24),
                          borderSide: BorderSide(
                            color: Theme.of(context).primaryColor.withOpacity(0.3),
                          ),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(24),
                          borderSide: BorderSide(
                            color: Theme.of(context).primaryColor.withOpacity(0.3),
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(24),
                          borderSide: BorderSide(
                            color: Theme.of(context).primaryColor.withOpacity(0.5),
                          ),
                        ),
                        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                        filled: true,
                        fillColor: Colors.grey.withOpacity(0.05),
                      ),
                      onSubmitted: (_) => _sendMessage(),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Container(
                    decoration: BoxDecoration(
                      color: _isLoading || !hasEnoughCoins
                          ? Theme.of(context).disabledColor 
                          : Theme.of(context).primaryColor,
                      shape: BoxShape.circle,
                    ),
                    child: IconButton(
                      icon: const Icon(Icons.send, color: Colors.white),
                      onPressed: _isLoading || !hasEnoughCoins ? null : _sendMessage,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class MessageBubble extends StatelessWidget {
  final ChatMessage message;

  const MessageBubble({Key? key, required this.message}) : super(key: key);

  void _showToast(String message) {
    Fluttertoast.showToast(
      msg: message,
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIosWeb: 1,
      backgroundColor: Colors.black54,
      textColor: Colors.white,
      fontSize: 16.0,
    );
  }

  @override
  Widget build(BuildContext context) {
    final isUser = message.isUser;
    return GestureDetector(
      onLongPress: !isUser ? () {
        final favoriteProvider = Provider.of<MessageFavoriteProvider>(context, listen: false);
        favoriteProvider.toggleFavorite(message);
        _showToast(favoriteProvider.isFavorite(message) 
            ? 'Added to favorites' 
            : 'Removed from favorites');
      } : null,
      child: Align(
        alignment: isUser ? Alignment.centerRight : Alignment.centerLeft,
        child: Container(
          margin: const EdgeInsets.symmetric(vertical: 4),
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
          decoration: BoxDecoration(
            color: isUser 
                ? Theme.of(context).primaryColor 
                : Theme.of(context).cardColor,
            borderRadius: BorderRadius.circular(20),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 2,
                offset: const Offset(0, 1),
              ),
            ],
          ),
          constraints: BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width * 0.7,
          ),
          child: Text(
            message.text,
            style: TextStyle(
              color: isUser ? Colors.white : null,
            ),
          ),
        ),
      ),
    );
  }
} 